const express = require('express')
const cors = require('cors')
const config = require('./config')
const logger = require('./middleware/logger')
const errorHandler = require('./middleware/errorHandler')
const path = require('path')
const fs = require('fs')

// 确保头像目录存在
const avatarsDir = path.join(process.cwd(), '..', 'public', 'avatars')
if (!fs.existsSync(avatarsDir)) {
  fs.mkdirSync(avatarsDir, { recursive: true })
}

const app = express()

app.use(cors(config.cors))
app.use(express.json())
app.use(logger)

// 静态文件服务
app.use('/avatars', express.static(avatarsDir))

// 路由
app.use('/api/users', require('./routes/users'))
app.use('/api/articles', require('./routes/articles'))
app.use('/api/profile', require('./routes/profile'))


// 错误处理
app.use(errorHandler)

const PORT = process.env.PORT || 3000
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`)
})

module.exports = app